package com.example.jbmsuppliers;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.support.annotation.Nullable;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.jbmsuppliers.bluetooth.le.DoorEvent;
import com.example.jbmsuppliers.bluetooth.le.OpenCtrl;
import com.example.jbmsuppliers.sinopec.activity.OvertActivity;
import com.example.jbmsuppliers.sinopec.sqlist.MySqliUtlis;
import com.example.jbmsuppliers.sinopec.utlis.OpenKey;
import com.example.jbmsuppliers.sinopec.utlis.SaveOpenKeyManage;
import com.example.jbmsuppliers.sinopec.view.MyToast;
import com.example.permission.myjbm.utils.LoginSharedPreferences;
import com.jbm.jbmsupplier.util.IEGuardKey;
import com.jbm.jbmsupplier.util.IEGuardKeyCtrl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * 李征
 * Created by 家帮忙 on 2017/1/3.
 */

public class MyDoorPreferTrue extends OvertActivity {
    @InjectView(R.id.clean_rotate)
    ImageView cleanRotate;
    @InjectView(R.id.clean_icon)
    ImageView cleanIcon;
    @InjectView(R.id.shortcut)
    RelativeLayout shortcut;
    @InjectView(R.id.te_door_kaimen)
    TextView teDoorKaimen;
    @InjectView(R.id.framelayout)
    LinearLayout framelayout;
    private SharedPreferences sharedPreferences,sharedPreferenceslog;
    private ArrayList<IEGuardKey> arr;
    private SharedPreferences.Editor sharlog;
    private String info;
    private Timer ti;
    private Vibrator vibratorr;
    private  SoundPool sp;
    private IEGuardKey egkeys;
    String tableopemerr="";
    private  int is_open;
    private  float Volume;
    private final int STOPWINDOW=0001;
    private final int CLEANSHAR=0002;
    private OpenCtrl ctrl;
    private IEGuardKeyCtrl iekc;
    private ArrayList<IEGuardKey> ArrayListIEKey;
    private LoginSharedPreferences openkeu;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_animation);
        ButterKnife.inject(this);
        ArrayListIEKey=new ArrayList<>();
        arr = new SaveOpenKeyManage(this).setgainOpenKey();
        iekc = new IEGuardKeyCtrl();
        ctrl = new OpenCtrl();
       openkeu= new LoginSharedPreferences(this);
        sharedPreferences = getSharedPreferences("open_key_judge", Activity.MODE_PRIVATE);
        sharedPreferenceslog = getSharedPreferences("open_door_log", Activity.MODE_PRIVATE);//保存蓝牙开门反馈给用户展示的信息
        sharlog= sharedPreferenceslog.edit();
        int open = sharedPreferences.getInt("intopen", 0);
//        boolean boo=sharedPreferences.getBoolean("boo",true);
//        if (boo){
//            stopService(new Intent(this, FloatWindowService.class));
//        }
        if (open != 1) {
            if (openkeu.getLoginState()!=true){
                MyToast.show(this,"登录后才能正常开门",0);
                finish();
            }else{
                String[] ffds = openkeu.getsaveOverDate().substring(0, openkeu.getsaveOverDate().indexOf(" ")).split("-");
            pdThreeDay(Integer.parseInt(ffds[0]),Integer.parseInt(ffds[1]),Integer.parseInt(ffds[2]));
            }
        } else {
            sharedPreferences.edit().clear().commit();
            MyToast.show(MyDoorPreferTrue.this,"请等待蓝牙恢复",0);
            finish();
        }
        AudioManager manager= (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int maxVolume = manager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        int currentVolume = manager.getStreamVolume(AudioManager.STREAM_MUSIC);
        Volume = currentVolume / (float) maxVolume;
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();

    }

    public void getWindowOpen() {
        if (arr==null)
            return;
        if (arr.size() > 0) {
            iekc.EGKlist = new IEGuardKey[arr.size()];
            for(int i=0;i<arr.size();i++) {
                if (arr.get(i).open_count == 0) {
                    hint("没有开门权限，请求分发或认证,+" + "\n" + "+请到我的页面手机开门设置认证");
                    return;
                } else {
                    iekc.EGKlist[i] = arr.get(i);
                }
            }
            cleanRotate.startAnimation(AnimationUtils.loadAnimation(this,R.anim.rotate_anim));
            setpp();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {vibratorr.cancel();
                }
            }, 500);

            ctrl.Open(1333, 3, iekc,getApplicationContext(), this, new DoorEvent() {
                @Override
                public void OpenSuccess(IEGuardKey egkey, String mac) {
                    SetCheckoutOpenCount(egkey);
                    egkeys=egkey;
                    is_open=1;
                    tableopemerr="开门成功";
                    sharlog.putString("info",tableopemerr).commit();
                    new Timer().schedule(new TimerTask() {
                        @Override
                        public void run() {
                            sp = new SoundPool(1, AudioManager.STREAM_SYSTEM, 0);//第一个参数为同时播放数据流的最大个数，第二数据流类型，第三为声音质量
                            sp.load(MyDoorPreferTrue.this, R.raw.dingdong, 1);
                            sp.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
                                @Override
                                public void onLoadComplete(SoundPool soundPool, int i, int i1) {
                                    soundPool.play(i,Volume,Volume,1,0,1);
                                }
                            });
                        }
                    },70);
                    handler.sendEmptyMessageDelayed(STOPWINDOW,2000);
                }
                @Override
                public void OpenFailed(IEGuardKey egkey, String mac) {
                    egkeys=egkey;
                    is_open=0;
                    tableopemerr="开门失败";
                    sharlog.putString("info",tableopemerr).commit();
                    handler.sendEmptyMessageDelayed(STOPWINDOW,2000);
                }
                @Override
                public void NotFound() {
                    is_open=0;
                    tableopemerr="未找到蓝牙设备";
                    sharlog.putString("info",tableopemerr).commit();
                    handler.sendEmptyMessageDelayed(STOPWINDOW,2000);
                }
                @Override
                public void OtherError(String errorinfo) {
                    is_open=0;
                    tableopemerr=errorinfo;
                    sharlog.putString("info",tableopemerr).commit();
                    handler.sendEmptyMessageDelayed(STOPWINDOW,2000);
                }

                @Override
                public void OpenStatus(String info) {
                    sharlog.putString("info",info).commit();
                }
            }, false);
            OpenKey.getinstant().setName("快捷开关");
            OpenKey.getinstant().setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis())));
            sharedPreferences.edit().putInt("intopen", 1).commit();
            if (ti==null){
                ti=  new Timer();
                ti.scheduleAtFixedRate(new RefreshTask(),0,500);
            }
        }else{

            new AlertDialog.Builder(this).setMessage("没有开门权限，请求分发或认证！").setTitle("开门失败").setCancelable(false).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    finish();
                }
            }).show();
        }



    }

    class RefreshTask extends TimerTask {
        @Override
        public void run() {
            info = sharedPreferenceslog.getString("info", "");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (!info.equals(""))
                        teDoorKaimen.setText(info);
                }
            });
        }
    }

    public void setpp() {
        vibratorr = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
        long[] pattern = {100, 400, 100, 400}; // 停止 开启 停止 开启
        vibratorr.vibrate(pattern, -1);
    }



Handler handler=new Handler(){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        switch (msg.what){
            case STOPWINDOW:
                getkaimen();
                cleanRotate.clearAnimation();
                handler.sendEmptyMessageDelayed(CLEANSHAR,8000);
                finish();
                break;
            case CLEANSHAR:{
                sharlog.clear().commit();
                sharedPreferences.edit().clear().commit();
                if(ti!=null){
                    ti.cancel();
                    ti=null;}
                break;
            }
        }

    }
};

private void SetCheckoutOpenCount(IEGuardKey egkey){
    for(int i=0;i<arr.size();i++){
        if (arr.get(i).open_key.equals(egkey.open_key)){
            if (egkey.open_total!=-1){
                int count= arr.get(i).open_count-1;
                egkey.open_count=count;
                egkeys=egkey;
            }else{

            }
        }
    }
    if (egkey.open_total==-1){
        egkeys=egkey;
    }
    ArrayListIEKey.add(egkeys);
    new SaveOpenKeyManage(MyDoorPreferTrue.this).setsaveOpenkey(ArrayListIEKey);
}



    public void getkaimen() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());
        String date = formatter.format(curDate);
        try {
            if (tableopemerr.equals("")) {
                return;
            }
            if(egkeys==null){
                MySqliUtlis.getInstance(this).Opendatakey(Integer.parseInt(GainLoginID("login_id")),0,0,0, date, date,is_open,0, Build.MODEL+Build.VERSION.RELEASE, OpenKey.getinstant().getName(),OpenKey.getinstant().getTime(),date,tableopemerr);
            }else {
                MySqliUtlis.getInstance(this).Opendatakey(Integer.parseInt(GainLoginID("login_id")), egkeys.eguard_id, egkeys.egkey_id, egkeys.open_count, date, date, is_open, 0, Build.MODEL + Build.VERSION.RELEASE, OpenKey.getinstant().getName(), OpenKey.getinstant().getTime(), date, tableopemerr);
            }
        } catch (Exception e) {
        }
    }


    public void pdThreeDay(int...arr){
        Calendar c = Calendar.getInstance(Locale.CHINA);
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int  day = c.get(Calendar.DAY_OF_MONTH);
        month+=1;
        //同年
        if(year==arr[0]){
            //同月
            if(arr[1]==month){
                //到三天了
                if(arr[2]-day<=3){
                    hint("开门期限还剩三天请及时更新");
                    getWindowOpen();
                }else{
                    //没有到
                    getWindowOpen();
                }
            }else{
                //不同月
                getWindowOpen();
            }
        }else{
            //不同年
            getWindowOpen();
        }
    }



}
